package com.ray.finance.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.base.service.BaseCustomerService;
import com.ray.base.table.entity.BaseCustomer;
import com.ray.common.SysMsgCodeConstant;
import com.ray.finance.check.AdvanceCheck;
import com.ray.finance.enums.AdvanceTypeEnum;
import com.ray.finance.service.FinaAdvanceDetailService;
import com.ray.finance.service.FinaAdvanceService;
import com.ray.finance.table.dto.AdvanceQueryDTO;
import com.ray.finance.table.entity.FinaAdvance;
import com.ray.finance.table.params.advance.AdvanceCreateParams;
import com.ray.finance.table.params.advance.AdvanceEditParams;
import com.ray.finance.table.params.advance.AdvanceQueryParams;
import com.ray.finance.table.vo.AdvanceDetailVO;
import com.ray.finance.table.vo.AdvanceVO;
import com.ray.magicBlock.BlockDispatch;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.system.enums.FileTypeEnum;
import com.ray.system.service.SysFileService;
import com.ray.system.table.entity.SysFile;
import com.ray.util.FileRecordUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.config.SysFileConfig;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 预付款单
 * @Class: AdvanceApi
 * @Package com.ray.finance.api
 * @date 2020/6/15 15:35
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
@Service
public class AdvanceApi {

    @Autowired
    private FinaAdvanceService finaAdvanceService;
    @Autowired
    private FinaAdvanceDetailService finaAdvanceDetailService;
    @Autowired
    private BlockDispatch<AdvanceCreateParams, LoginUser, String> createDispatch;
    @Autowired
    private BlockDispatch<AdvanceEditParams, LoginUser, String> editDispatch;
    @Autowired
    private BlockDispatch<FinaAdvance, LoginUser, String> deleteDispatch;
    @Autowired
    private BaseCustomerService baseCustomerService;
    @Autowired
    private SysFileService sysFileService;
    @Autowired
    private SysFileConfig sysFileConfig;


    /**
     * 查询订单列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<AdvanceVO>> pageAdvances(CommonPage<AdvanceQueryParams, Page<AdvanceVO>> queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        Map<String, BaseCustomer> baseCustomerMap = new HashMap<>();
        CommonPageBuilder<AdvanceQueryDTO, FinaAdvance> commonPageBuilder = new CommonPageBuilder<>(AdvanceQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<FinaAdvance> page = finaAdvanceService.page(commonPageBuilder.bulid(), loginUser);
        List<FinaAdvance> orders = page.getRecords();
        //结果对象
        IPage<AdvanceVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(orders)) {
            pageList.setRecords(orders.stream().map(sysAdvance -> {
                AdvanceVO advanceVO = new AdvanceVO();
                //查询客信息
                BaseCustomer baseCustomer = baseCustomerMap.get(sysAdvance.getCustomerCode());
                if (ObjectUtil.isEmpty(baseCustomer)) {
                    baseCustomer = baseCustomerService.queryCustomerByCustomerCode(sysAdvance.getCustomerCode(), loginUser);
                    baseCustomerMap.put(sysAdvance.getCustomerCode(), baseCustomer);
                }
                if (ObjectUtil.isNotNull(baseCustomer)) {
                    advanceVO.setCustomerName(baseCustomer.getCustomerName());
                }
                BeanUtil.copyProperties(sysAdvance, advanceVO);
                return advanceVO;
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }


    /**
     * 创建预付款单
     *
     * @return
     */
    @Transactional
    public Result<String> createAdvance(AdvanceCreateParams createParams, AdvanceTypeEnum advanceTypeEnum) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        String advanceCode = createDispatch.dispatch("createAdvance", advanceTypeEnum.getValue(), createParams, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, advanceCode);
    }

    /**
     * 删除
     *
     * @return
     */
    @Transactional
    public Result<String> editAdvance(AdvanceEditParams editParams) {
        Assert.notNull(editParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        FinaAdvance finaAdvance = finaAdvanceService.queryAdvanceByAdvanceCode(editParams.getAdvanceCode(), loginUser);
        new AdvanceCheck(finaAdvance).checkNull("预付款单不存在");
        //编辑业务单
        editDispatch.dispatch("editAdvance", finaAdvance.getType(), editParams, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, editParams.getAdvanceCode());
    }


    /**
     * 删除
     *
     * @return
     */
    @Transactional
    public Result<String> deleteAdvance(String advanceCode) {
        Assert.hasLength(advanceCode, "参数[advanceCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        FinaAdvance finaAdvance = finaAdvanceService.queryAdvanceByAdvanceCode(advanceCode, loginUser);
        new AdvanceCheck(finaAdvance).checkNull("预付款单不存在");
        //取消业务单
        deleteDispatch.dispatch("deleteAdvance", finaAdvance.getType(), finaAdvance, loginUser);
        finaAdvanceDetailService.deleteByAdvanceCode(advanceCode, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, advanceCode);
    }


    /**
     * 预付款单详情
     *
     * @param advanceCode
     * @return
     */
    public Result<AdvanceVO> viewAdvance(String advanceCode) {
        Assert.hasLength(advanceCode, "参数[advanceCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        FinaAdvance finaAdvance = finaAdvanceService.queryAdvanceByAdvanceCode(advanceCode, loginUser);
        new AdvanceCheck(finaAdvance).checkNull("预付款单不存在");
        //查询客信息
        BaseCustomer baseCustomer = baseCustomerService.queryCustomerByCustomerCode(finaAdvance.getCustomerCode(), loginUser);
        AdvanceVO advanceVO = new AdvanceVO();
        if (ObjectUtil.isNotNull(baseCustomer)) {
            advanceVO.setCustomerName(baseCustomer.getCustomerName());
        }
        BeanUtil.copyProperties(finaAdvance, advanceVO);
        //查询附件
        //查询图片信息
        List<SysFile> files = sysFileService.queryFiles(advanceCode, FileTypeEnum.ADVANCE.getValue(), loginUser);
        advanceVO.setFiles(FileRecordUtil.toFileVO(files, sysFileConfig));
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, advanceVO);
    }


    /**
     * 预付款单详情
     *
     * @param advanceCode
     * @return
     */
    public Result<List<AdvanceDetailVO>> viewAdvanceDetail(String advanceCode) {
        Assert.hasLength(advanceCode, "参数[advanceCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();

        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, finaAdvanceDetailService.listByAdvanceCode(advanceCode, loginUser).stream()
                .map(advanceDetail -> {
                    AdvanceDetailVO advanceDetailVO = new AdvanceDetailVO();
                    BeanUtil.copyProperties(advanceDetail,advanceDetailVO);
                    return advanceDetailVO;
                }).collect(Collectors.toList())
        );
    }

}
